import axios from 'axios';
import { message } from 'antd';
import { history } from 'umi';

const request = axios.create({
  timeout: 5000,
  baseURL: "/api/"
})

request.interceptors.request.use(
  (config) => {
    let token = sessionStorage.getItem("token");
    // @ts-ignore
    config.headers["Authorization"] = token
    // @ts-ignore
    config.headers["Accept"] = "application/json";

    return config;
  },
  (error) => {
    return Promise.reject(error)
  }
)

request.interceptors.response.use(
  (response) => {
    const res = response.data;

    if (res.code === 1) {
      message.error(
        res.message || 'Error',
        5000
      ).then((err) => {
        console.log(err)
      })
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res;
    }
  },
  (error) => {
    if (
      error.response &&
      error.response.status !== 400 &&
      error.response.status !== 401 &&
      error.response.status !== 409
    ) {
      message.error(
        (error.response &&
          error.response.data &&
          error.response.data.message) ||
        error.message,
        5000
      ).then((err) => {
        console.log(err)
      })
    }
    if (error.response && error.response.status === 401) {
      message.error(
        "登录已经失效！",
        5000
      ).then((err) => {
        console.log(err)
      })
      setTimeout(function() {
        history.push("/login")
      }, 1000);
    }
    if (error.response && error.response.status === 400) {
      message.error(
        error.response.data.message,
        5 * 1000
      ).then((err) => {
        console.log(err)
      })
    }
    return Promise.reject(error);
  }
);

export default request;
